package com.android.bonn.fast.adapter.ext

import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.android.bonn.fast.adapter.*
import com.android.bonn.fast.adapterlayout.AdapterLayout

fun RecyclerView.buildCells() = SimpleCellDelegateAdapter.Builder()

inline fun <T : Any> SimpleCellDelegateAdapter.Builder.create(
  resId: Int,
  crossinline createCell: (View) -> CellView<T>,
  crossinline type: (Int, Any) -> Boolean,
  noinline click: ((View, Int, T) -> Unit)? = null
): SimpleCellDelegateAdapter.Builder {

  return if (click != null) {
    val listener = OnItemViewClickListener<T> { view, position, data -> click(view, position, data) }
    putItem(cellViewCreator(resId, createCell, type), listener)
  } else {
    putItem(cellViewCreator(resId, createCell, type))
  }
}


inline fun <T> cellViewCreator(
  resId: Int,
  crossinline createCell: (View) -> CellView<T>,
  crossinline type: (Int, Any) -> Boolean,
) = object : CellViewCreator<T, CellView<T>>() {

  override fun create(view: View): CellView<T> = createCell(view)

  override fun isCellViewType() = CellViewType { position, model -> type(position, model) }

  override fun getItemViewId() = resId

  override fun hashCode() = resId
}

class Creator<T>(
  private val resId: Int,
  private val createCell: (View) -> CellView<T>,
  private val type: (Int, Any) -> Boolean = { _, _ -> true }
) : CellViewCreator<T, CellView<T>>() {

  override fun create(itemView: View): CellView<T> = createCell(itemView)

  override fun isCellViewType() = CellViewType { position, model -> type(position, model) }

  override fun getItemViewId() = resId

}


fun RecyclerView.ViewHolder.getAdapterLayoutAdapterPosition(): Int {
  return AdapterLayout.getAdapterPosition(this)
}

fun RecyclerView.ViewHolder.getAdapterLayoutLayoutPosition(): Int {
  return AdapterLayout.getLayoutPosition(this)
}